<%@ page import="admin.Connectmysql" %>
<%@ page import="java.util.ArrayList" %>
<%@ page import="java.sql.ResultSet" %>
<%@ page import="admin.Classes" %>
<%@ page import="java.util.List" %>
<%@ page import="java.sql.SQLException" %><%--
  Created by IntelliJ IDEA.
  User: ASUS
  Date: 2025/6/22
  Time: 10:20
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>

<%!
    String escapeJson(String value) {
        if (value == null) return "";
        return value.replace("\\", "\\\\")
                .replace("\"", "\\\"")
                .replace("\n", "\\n")
                .replace("\r", "\\r")
                .replace("\t", "\\t");
    }
%>
<%
    List<Classes> teachers = new ArrayList<>();
    Connectmysql cmysql = new Connectmysql(
            "jdbc:mysql://localhost:3306/exam1",
            "root",
            "root",
            "com.mysql.cj.jdbc.Driver");
    try {
        if(cmysql.open()){

            ResultSet rst= cmysql.executeSql(
                    "SELECT * FROM class;",
                    new Object[]{}
            );
            while (rst.next()) {
                Classes teacher = new Classes(
                        rst.getString("class_id"),
                        rst.getString("class_name"),
                        rst.getString("description"),
                        rst.getString("head_teacher"),
                        rst.getString("create_time")
                );
                teachers.add(teacher);
            }
            //Gson gson = new Gson();
            StringBuilder json = new StringBuilder("[");

            for (int i = 0; i < teachers.size(); i++) {
                Classes teacher = teachers.get(i);

                json.append("{");
                json.append("\"id\":\"").append(escapeJson(teacher.getId())).append("\",");
                json.append("\"name\":\"").append(escapeJson(teacher.getName())).append("\",");
                json.append("\"description\":\"").append(escapeJson(teacher.getDescription())).append("\",");
                json.append("\"headTeacher\":\"").append(escapeJson(teacher.getHeadTeacher())).append("\",");
                json.append("\"studentCount\":\"").append(escapeJson("30")).append("\",");
                json.append("\"createTime\":\"").append(escapeJson(teacher.getCreatTime())).append("\"");
                json.append("}");

                if (i < teachers.size() - 1) {
                    json.append(",");
                }
            }
            json.append("]");
            // 输出JSON
            response.setContentType("application/json");
            response.setCharacterEncoding("UTF-8");
            response.getWriter().write(json.toString());
            rst.close();
        }
    } catch (ClassNotFoundException f) {
        f.printStackTrace();
    } catch (SQLException throwables) {
        throwables.printStackTrace();
    }

%>